#include "app_pool.h"
#include "log/log.h"
#include <mqueue.h>
#include <pthread.h>
#include <stdio.h>
#include <stdlib.h>
#include <string.h>
#include <unistd.h>

static char *mq_name = "/app_pool_mq";
static mqd_t mqd;
static pthread_t *threads; // 线程池(保存所有线程的标识)
static int thread_num = 0; // 线程池中线程的数量

void *thread_func(void *arg)
{
    // 不断从消息队列中获取任务并执行
    Task task;
    while (1)
    {
        ssize_t size = mq_receive(mqd, (char *)&task, sizeof(Task), NULL);
        if (size == sizeof(Task))
        {
            task.taks_func(task.arg);
        }
    }
}
int app_pool_init(int size)
{
    struct mq_attr attr;
    attr.mq_msgsize = sizeof(Task);
    attr.mq_maxmsg = 10;
    // 创建消息队列
    mqd = mq_open(mq_name, O_CREAT | O_RDWR, 0666, &attr);
    if (mqd == -1)
    {
        log_error("mq_open failed");
        return -1;
    }
    // 创建线程池
    thread_num = size;
    // 给线程池分配空间
    threads = (pthread_t *)malloc(sizeof(pthread_t) * thread_num);
    for (int i = 0; i < thread_num; i++)
    {
        pthread_create(&threads[i], NULL, thread_func, NULL);
    }
    return 0;
}

void app_pool_close(void)
{
    // 关闭消息队列
    mq_close(mqd);
    // 删除消息队列
    mq_unlink(mq_name);
    // 销毁线程池
    for (int i = 0; i < thread_num; i++)
    {   
        pthread_cancel(threads[i]);
        pthread_join(threads[i], NULL);
    }
    free(threads);
}

int app_pool_registerTask(int (*taks_func)(void *), void *arg)
{
    // 创建任务
    Task task = {.taks_func = taks_func, .arg = arg};
    mq_send(mqd, (char *)&task, sizeof(Task), 0);

    return 0;
}

